<template>
  <div class="navbar" :class="{ 'small-search-box': useClass == 'fixed-show' }">
    <div class="container width_1200_auto flex flex-a-c">
      <img :src="$store.state.logoImg" v-if="showLogo" class="logo-img" alt="" @click="$router.push('/')" />
      <div :class="{ 'small-search-box': useClass == 'fixed-show' }" class="search-box">
        <div class="ul">
          <span class="title">需求分类</span>
          <span class="span" v-for="(item, i) in type" @click="handleHistoryClick(item)" :key="i">{{ item.label
          }}</span>
        </div>
        <div class="search-boxi">
          <i-input v-model="searchData" style="width:calc(100% - 120px);" size="large" class="search"
            placeholder="输入你想查找内容" @keyup.enter.native="search">
            <div class="search-icon" slot="append" @click="search">
              <Icon type="ios-search" size="21" />
            </div>
          </i-input>
          <div class="search-boxi_botton" v-if="role != 'writers'" @click="NewSearch">发布需求</div>
        </div>
        <div v-if="searchHistory.length" class="history-list-container">
          <h3 class="history-title">搜索历史记录</h3>
          <ul class="history-list1">
            <!---->
            <li v-for="(item, index) in searchHistory" @click="handleHistoryClick(item)" :key="index"
              class="history-item">
              {{ item.label }}
              <!-- <span @click.stop="deleteHistory(item.id)" class="delete-btn">删除</span> -->
            </li>
          </ul>
          <!-- <button @click="clearHistory" class="clear-history-btn">清除历史记录</button> -->
        </div>

        <template v-if="showTag">
          <div class="only-store" v-if="storeId" @click="research()">
            切换为{{ !onlyStore ? "店铺内" : "平台" }}搜索
          </div>
          <div v-if="promotionTags.length === 0"></div>
          <div v-else class="history-list flex">
            <div v-for="(item, index) in promotionTags" :key="index" class="mr_10">
              <!-- <span class="history-item" @click="selectTags(item)">{{
                item
              }}</span> -->
            </div>
          </div>
        </template>
      </div>
    </div>
    <Modal v-model="modal" :title="title" width="60%" @on-close="cancel">
      <Form ref="formValidates" :model="formValidate" :rules="ruleValidate" :label-width="100">
        <Row>
          <Col span="15">
          <FormItem label="需求类型" prop="type">
            <Select v-model="clickType" @on-change="clickTypeFun" multiple placeholder="请选择需求类型">
              <Option v-for="(item, i) in type" :value="item.value" :key="i">{{ item.label }}</Option>
              <!-- <Option value="shanghai">ppt</Option>
              <Option value="shenzhen">pdf</Option>
              <Option value="other">其他</Option> -->
            </Select>
          </FormItem>
          <!-- </Col>
          <Col span="11"> -->
          <FormItem label="需求标题" prop="title">
            <Input v-model="formValidate.title" placeholder="请输入需求标题"></Input>
          </FormItem>
          <!-- </Col>
        </Row>

        <Row>
          <Col span="11"> -->
          <FormItem label="需求描述" prop="content">
            <Input v-model="formValidate.content" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }"
              placeholder="请输入需求描述"></Input>
          </FormItem>
          <!-- </Col>
          <Col span="11"> -->
          <FormItem label="附件上传" prop="file">
            <FileUpload @input="FileUploadInput" :value="formValidate.file"></FileUpload>
          </FormItem>
          <!-- </Col>
        </Row>
        <Row>
          <Col span="11"> -->
          <!-- <FormItem label="佣金金额" prop="price">
            <Input v-model="formValidate.price" placeholder="请输入佣金金额"></Input>
          </FormItem> -->
          <!-- </Col>
          <Col span="11"> -->
          <FormItem label="需求起止时间" prop="startTime">
            <DatePicker type="datetimerange" :options="options" v-model="date" @on-change="handleClickDate"
              placeholder="开始时间-结束时间" style="width: 240px" />
          </FormItem>
          <!-- </Col>
        </Row>
        <Row>
          <Col span="11"> -->
          <FormItem label="备注">
            <Input v-model="formValidate.remark" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }"
              placeholder="请输入备注"></Input>
          </FormItem>
          <!-- </Col>
          <Col span="11"> -->
          <FormItem label="其他需求">
            <Input v-model="formValidate.other" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }"
              placeholder="请输入其他需求"></Input>
          </FormItem>
          <!-- </Col> -->
          <!-- <Col span="11">
          <FormItem label="新增类型" prop="number">
            <Select v-model="formValidate.number" placeholder="请选择新增类型">
              <Option value="1">首次新增</Option>
              <Option value="2">二次创作</Option>
            </Select>
          </FormItem> -->
          </Col>
        </Row>
        <Checkbox v-model="single">协议勾选有客户提供二次点击后跳转内容</Checkbox>
      </Form>
      <div slot="footer">
        <Button @click="cancel">取消</Button>
        <Button style="background-color: #ff5343;color: #fff;" @click="handleSubmit('formValidates')">确认</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import storage from "@/plugins/storage.js";
import { saveDesired, getOrderTypeList, getSearchList } from "@/api/writer/index.js";
import { Message, Spin, Modal } from 'view-design';
import { hotWords } from "@/api/goods.js";
import { EventBus } from '@/plugins/EventBus';

export default {
  name: "search",
  props: {
    showTag: {
      // 是否展示搜索栏下方热门搜索
      type: Boolean,
      default: true,
    },
    showLogo: {
      // 是否展示左侧logo
      type: Boolean,
      default: true,
    },
    storeId: {
      // 是否为店铺页面
      type: String,
      default: "",
    },
    hover: {
      type: Boolean,
      default: false,
    },
    useClass: {
      type: null,
      default: "",
    },
  },
  watch: {
    storeId(val) {
      this.onlyStore = val ? true : false;
    },
  },
  data() {
    return {
      searchData: "", // 搜索内容
      onlyStore: false,
      modal: false,
      title: "新增需求",
      single: false,
      formValidate: {
        type: null,
        title: '',
        content: '',
        file: [],
        price: null,
        remark: '',
        other: '',
        startTime: '',
        endTime: '',
        number: '1'
      },
      clickType: [],
      value: '',
      date: [],//日期
      type: [],//需求类型
      ruleValidate: {
        type: [
          { required: true, message: '请选择需求类型', trigger: 'blur' }
        ],
        number: [
          { required: true, message: '请选择新增类型', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '请输入需求标题', trigger: 'blur' },
        ],
        content: [
          { required: true, message: '请输入需求描述', trigger: 'blur' }
        ],
        file: [
          { required: true, message: '请选择附件上传', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入佣金金额', trigger: 'blur' },
          {
            pattern: /^\d+(\.\d{1,2})?$/,
            message: '请输入整数或两位小数',
            trigger: 'change'
          }
        ],
        startTime: [
          { required: true, message: '请选择日期', trigger: 'change' }
        ],
      },
      role: '',
      searchHistory: [],
      searchKeyword: '',
      options: {
        disabledDate(date) {
          return date && date.valueOf() < Date.now() - 86400000;
        }
      },
    };
  },

  mounted() {
    this.GetOrderTypeList();
    // 页面加载时获取搜索历史记录
    if (storage.getItem("roles")) {
      this.role = storage.getItem("roles")
      this.getSearchHistory();
    }
  },
  methods: {
    selectTags(item) {
      // 选择热门标签
      this.searchData = item;
      this.search();
    },
    research() {
      this.onlyStore = !this.onlyStore;
    },
    search() {
      this.getSearchHistory()
      EventBus.$emit('message', this.searchData);
      // // 全平台搜索商品
      // const url = this.$route.path;
      // if (url == "/goodsList") {
      //   this.$emit("search", this.searchData);
      // } else {
      //   const pushData = {
      //     path: "/goodsList",
      //     query: { keyword: this.searchData },
      //   };
      //   if (this.storeId && this.onlyStore)
      //     pushData.query.storeId = this.storeId;

      //   this.$router.push(pushData);
      // }
    },
    searchStore() {
      // 店铺搜索商品
      this.$emit("search", this.searchData);
    },
    NewSearch() {
      const storedToken = storage.getItem('accessToken');
      const storedTime = storage.getItem('tokenTime');
      if (storedToken && storedTime) {
        const now = new Date().getTime();
        const diff = (now - parseInt(storedTime)) / (1000 * 60); // 计算时间差（分钟）
        if (diff > 300) {
          storage.removeItem('accessToken');
          storage.removeItem('refreshToken');
          storage.removeItem('userInfo');
          storage.removeItem('roles');
          Modal.confirm({
            title: '请登录',
            content: `<p>token已过期请重新登录</p>`,
            okText: '立即登录',
            cancelText: '继续浏览',
            onOk: () => {
              this.$router.push({
                path: '/login',
                query: {
                  rePath: this.$router.history.current.path,
                  query: JSON.stringify(this.$router.history.current.query)
                }
              });
            },
            onCancel: () => {
              // router.go(0)
              this.$router.push("/");
              Modal.remove();
            }
          });
        } else {
          this.clickType = ''
          this.single = false
          this.formValidate = {
            type: null,
            title: '',
            content: '',
            file: [],
            price: null,
            remark: '',
            other: '',
            startTime: '',
            endTime: '',
            number: null
          }
          this.modal = true;
          this.title = "新增需求";
        }
      } else {
        storage.removeItem('accessToken');
        storage.removeItem('refreshToken');
        storage.removeItem('userInfo');
        storage.removeItem('roles');
        Modal.confirm({
          title: '请登录',
          content: `<p>请先登录在执行此操作</p>`,
          okText: '立即登录',
          cancelText: '继续浏览',
          onOk: () => {
            this.$router.push({
              path: '/login',
              query: {
                rePath: this.$router.history.current.path,
                query: JSON.stringify(this.$router.history.current.query)
              }
            });
          },
          onCancel: () => {
            // router.go(0)
            this.$router.push("/");
            Modal.remove();
          }
        });
      }

    },
    handleSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          if (!this.single) {
            this.$Message.error('请勾选协议!');
            return
          }
          const params = {
            id: 0,
            userId: JSON.parse(storage.getItem("userInfo")).userId,
            ...this.formValidate,
          }
          saveDesired(params).then(res => {
            console.log(res, "保存需求订单");
            if (res.code == 200) {
              this.$Message.success('保存成功!');
              EventBus.$emit('message', '');
              this.modal = false;
            }
          })
        } else {
          this.$Message.error('请填写完整信息!');
        }
      })
    },
    cancel() {
      this.modal = false;
      this.clickType = ''
      this.date = []
      this.formValidate = {
        type: null,
        title: '',
        content: '',
        file: [],
        price: null,
        remark: '',
        other: '',
        startTime: '',
        endTime: '',
        number: null
      }
    },
    //获取订单类型
    GetOrderTypeList() {
      getOrderTypeList().then(res => {
        this.type = res.data.map(x => {
          return {
            label: x.name,
            value: x.id
          }
        })
      })
    },
    //日期选择
    handleClickDate(val) {
      console.log(val, "val");
      this.formValidate.startTime = val[0]
      this.formValidate.endTime = val[1]
    },
    //上传附件
    FileUploadInput(file) {
      // console.log(file, "file");
      this.formValidate.file = file
    },
    clickTypeFun(val) {
      console.log(val, "val");
      this.formValidate.type = val.join(',')
    },
    // 获取搜索历史记录
    async getSearchHistory() {
      try {
        const response = await getSearchList()
        if (!response.data) return
        const uniqueTitles = {};
        let newArr = response.data.records.map(el => {
          return {
            label: el.title,
            value: el.id,
          };
        });
        this.searchHistory = newArr.concat(this.type).filter(el => {
          if (!uniqueTitles[el.label]) {
            uniqueTitles[el.label] = true;
            return true;
          }
          return false;
        })
        // console.log(this.searchHistory, this.type, '????????');
      } catch (error) {
        console.error('获取搜索历史记录失败:', error);
      }
    },
    // 处理搜索操作
    // async handleSearch() {
    //   if (this.searchKeyword.trim()) {
    //     // 调用接口添加新的搜索历史记录
    //     try {
    //       const response = await axios.post('/search-history', { keyword: this.searchKeyword });
    //       // 成功后更新本地的搜索历史记录列表
    //       this.getSearchHistory();
    //       // 这里可以添加实际的搜索逻辑，例如调用 API 进行搜索
    //       console.log(`搜索关键词: ${this.searchKeyword}`);
    //       this.searchKeyword = '';
    //     } catch (error) {
    //       console.error('添加搜索历史记录失败:', error);
    //     }
    //   }
    // },
    // 点击历史记录进行搜索
    async handleHistoryClick(item) {
      this.searchData = item.label
      this.search();
    },
    // 删除单条历史记录
    // async deleteHistory(id) {
    //   try {
    //     await axios.delete(`/search-history/${id}`);
    //     // 成功后更新本地的搜索历史记录列表
    //     this.getSearchHistory();
    //   } catch (error) {
    //     console.error('删除搜索历史记录失败:', error);
    //   }
    // },
    // 清除搜索历史记录
    // async clearHistory() {
    //   try {
    //     // 假设后端有一个接口用于清空所有历史记录
    //     await axios.delete('/search-history');
    //     // 成功后更新本地的搜索历史记录列表
    //     this.getSearchHistory();
    //   } catch (error) {
    //     console.error('清除搜索历史记录失败:', error);
    //   }
    // }
  },
  computed: {
    promotionTags() {
      if (this.$store.state.hotWordsList) {
        return JSON.parse(this.$store.state.hotWordsList);
      } else {
        return [];
      }
    },
  },
  created() {
    this.searchData = this.$route.query.keyword;

    // if (!this.hover) {
    //   // 首页顶部固定搜索栏不调用热词接口
    //   // 搜索热词每5分钟请求一次
    //   const reloadTime = storage.getItem("hotWordsReloadTime");
    //   const time = new Date().getTime() - 5 * 60 * 1000;
    //   if (!reloadTime) {
    //     hotWords({ count: 5 }).then((res) => {
    //       if (res.success && res.result)
    //         storage.setItem("hotWordsList", res.result);
    //     });
    //     storage.setItem("hotWordsReloadTime", new Date().getTime());
    //   } else if (reloadTime && time > reloadTime) {
    //     hotWords({ count: 5 }).then((res) => {
    //       if (res.success && res.result)
    //         storage.setItem("hotWordsList", res.result);
    //     });
    //     storage.setItem("hotWordsReloadTime", new Date().getTime());
    //   }
    // }
  },
};
</script>
<style scoped lang="scss">
.only-store {
  text-align: right;
  color: $theme_color;
  cursor: pointer;
}

.navbar {
  height: 180px;
  background: #fff;
}

.search-icon {
  width: 100%;
  height: 100%;
}

.small-search-box {
  height: 60px;

  margin: 0 !important;
}

.container {
  position: relative;

  height: 100%;

  .ul {
    display: flex;
    align-items: center;
    margin-bottom: 10px;

    .title {
      color: #333;
      font-weight: 600;
      margin-right: 10px;
      font-size: 15px;

    }

    .span {
      font-size: 14.5px;
      padding: 0 15px;
      border-right: 1px solid #cccbcb;
      height: 16px;
      line-height: 16px;
      cursor: pointer;
    }

    .span:last-child {
      border: 0;
    }

  }
}

.search {
  width: 778.4px;
  margin: 10px 0px 5px 0;

  border-radius: 18.9px;

  ::v-deep .ivu-input.ivu-input-large {
    border: 1.4px solid $theme_color;
    box-sizing: border-box;
    border-radius: 19.6px;
    position: relative;
    padding-left: 26px;
    font-size: 14px;
    font-weight: normal;
    height: 37.8px;
    color: #999;

    &:focus {
      box-shadow: none;
    }
  }

  ::v-deep .ivu-input-group-append {
    border-radius: 19.6px !important;
    cursor: pointer;
    box-sizing: border-box;
    border: 1.4px solid $theme_color;
    width: 67.2px;
    height: 37.8px;
    position: absolute;
    right: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    top: 0;
    z-index: 99;
    background-color: $theme_color;
    color: #ffffff;

    button {
      font-size: 14px;
      font-weight: 600;
      line-height: 1;
    }
  }
}

.search-box {
  margin: 0 28px;
  width: 100%;

  .search-boxi {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;

    .search-boxi_botton {
      width: c;
      background-color: #f31947;
      color: #ffffff;
      padding: 11px 30px;
      border-radius: 25px;
      cursor: pointer;
    }
  }
}

.logo-img {
  max-width: 150px;
  cursor: pointer;
}

.store-search {
  width: 55.6px;
  padding: 0 9px;
  border-radius: 0;
  border-radius: 3px;

  &:nth-child(2) {
    width: 55px;
    margin-left: -2px;
    border-radius: 3px;
  }
}

.btn-div {
  position: relative;
  height: 0px;
  top: -38px;
  left: 352px;
}

.history-list {
  margin-left: 28px;
}

.history-item {
  font-size: 13px;
  font-weight: normal;
  line-height: 16px;
  letter-spacing: 0px;
  margin-right: 17px;
  color: #666666;
  cursor: pointer;
}

::v-deep .ivu-modal {
  top: calc(50% - 250px) !important;
}

.history-list-container {
  // display: flex;
  // margin-top: 10px;
}

.history-title {
  padding: 5px;
}

.history-list1 {
  display: flex;
}

.history-item {
  padding: 5px 10px;
  border-radius: 25px;
  background: #dddddd;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: background-color 0.3s ease;
}

.history-item:hover {
  background-color: #f4f4f4;
}

.delete-btn {
  color: #ff0000;
  cursor: pointer;
  font-size: 14px;
}

.clear-history-btn {
  margin-top: 10px;
  padding: 10px 20px;
  border: none;
  background-color: #dc3545;
  color: #fff;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.clear-history-btn:hover {
  background-color: #c82333;
}
</style>
